﻿using System.Threading.Tasks;
using Microsoft.AspNetCore.Http;

namespace PayService.Middleware
{
    public class JWTInHeaderMiddleware
    {
        private readonly RequestDelegate @delegate;

        public JWTInHeaderMiddleware(RequestDelegate requestDelegate)
        {
            @delegate = requestDelegate;
        }

        public async Task Invoke(HttpContext httpContext)
        {
            if (httpContext.Request.Cookies.TryGetValue("access_token", out string token))
            {
                httpContext.Request.Headers.Remove("Authorization");
                httpContext.Request.Headers.Add("Authorization", $"Bearere {token}");
            }

            await @delegate.Invoke(httpContext);
        }
    }
}
